package com.youlai.boot.system.service.impl;
import cn.hutool.core.lang.Assert;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.system.mapper.DeviceMapper;
import com.youlai.boot.system.model.QB.Device;
import com.youlai.boot.system.model.QB.DeviceInfoVO;
import com.youlai.boot.system.service.DeviceService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;

@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements DeviceService {
    private static final Logger logger = LoggerFactory.getLogger(DeviceServiceImpl.class);
    @Autowired
    private  DeviceMapper deviceMapper ;



    @Override
    public boolean addDevice(Device device) {
        Assert.isFalse(this.exists(new LambdaQueryWrapper<Device>().eq(Device::getDevicenumber,device.getDevicenumber())),"设备编号已经存在");

        //设置添加时间为当前时间
        device.setStatus(1);
        if(device.getPicUrls() != null && !device.getPicUrls().isEmpty()){
            String picUrl = "";
            for (String str : device.getPicUrls()) {
                picUrl +=  str+",";
            }
            if(StringUtils.isNotBlank(picUrl)) {
                device.setPicUrl(picUrl.substring(0,picUrl.length() -1));
            }
        }
//        device.setAddTime(LocalDateTime.now());
        //添加设备后默认状态为1（启用状态）

        return save(device);

    }
/*
查询所有设备
 */
    @Override
    public List<Device> getAllDevice() {
        return deviceMapper.selectList(null);
    }

    @Override
    public Device getDeviceByNumber(String devicenumber) {

        return deviceMapper.selectByDeviceNumber(devicenumber);
    }

    @Override
    public boolean updateDeviceStatus(String deviceNumber, int newStatus) {

        Device device = lambdaQuery()
                .eq(Device::getDevicenumber,deviceNumber)
                .one();
        if (device == null){
            logger.info("未找到相应的设备编号{},无法修改状态" + deviceNumber);
            return  false;
        }
        device.setStatus(newStatus);
        device.setUpdateTime(LocalDateTime.now());

        boolean result = updateById(device);
        if (result){
            logger.info("设备{}状态已修改成为{}" + deviceNumber,newStatus);

        }else {
            logger.error("设备状态修改失败" + deviceNumber);
        }
        return result;
    }

    @Override
    public List<DeviceInfoVO> getDeviceInfo(String devicenumber) {
        logger.info("在Mapper层接收到的设备编号参数：{}", devicenumber);
        List<DeviceInfoVO> result = null;
        // 这里执行具体的查询操作，假设使用MyBatis，示例如下：
        try {
            return baseMapper.selectDeviceInfo(devicenumber);
//            result = this.selectList(new QueryWrapper<Device>().lambda()
//                    .eq(Device::getDevicenumber, devicenumber));
//            logger.info("在Mapper层查询结果：{}", devicenumber);
        } catch (Exception e) {
            logger.error("在Mapper层查询时发生错误：", e);
        }
        return result;
    }

    @Override
    public List<DeviceInfoVO> selectList(LambdaQueryWrapper<Device> eq) {
        return null;
    }

    @Override
    public boolean updateDevice(Device device) {
        if (device ==null){
            logger.error("未查到相应设备，请重新查询");
            return false;
        }
        if (device.getPicUrls() != null && device.getPicUrls().size() > 0){
            String picUrl = "";
            for (String str : device.getPicUrls()){
                picUrl += str + ",";
            }
            if (org.apache.commons.lang3.StringUtils.isNotBlank(picUrl)){
                picUrl = picUrl.substring(0,picUrl.length()-1);
            }
            device.setPicUrl(picUrl);
        }


        logger.info("尝试更新设备信息设备编号为：" + device.getDevicenumber());
        boolean resulf = baseMapper.updateById(device) >0;
        if (resulf){
            logger.info("设备更新成功，设备编号为：" + device.getDevicenumber());
        }else {
            logger.warn("设备更新失败，设备编号为：" + device.getDevicenumber());
        }
        return resulf;
    }

    @Override
    public boolean deleteDeviceById(Integer id) {
        return deviceMapper.deleteById(id) > 0;
    }

//    @Override
//    public boolean addDeviceUsageRecordById(Long id, String usagePurpose, LocalDateTime usageTime) {
//        Device device = new Device();
//        device.setId(id);
//        device.setUsagePurpose(usagePurpose);
//        device.setUsageTime(usageTime);
//
//        return getBaseMapper().insertUsageRecordById(device) > 0;
//    }

}

//    @Override
//    public boolean addDeviceUsageRecord(Long id) {
//        QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("id", id);
//        return deviceMapper.exists(queryWrapper);
//
//        }


